package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/flosch/pongo2"
	"net/http"
	"github.com/mojocn/base64Captcha"
	"fmt"
	"titargo/forms"
	"titargo/models"
	"github.com/gorilla/sessions"
)

var homeFunc = func(c *gin.Context) {
	c.HTML(http.StatusOK, "site/index.twig", TplContext(c))
}

var notFoundFunc = func(c *gin.Context){
	c.HTML(http.StatusOK,"404.twig",TplContext(c))
}

var captchaFunc = func(c *gin.Context) {
	var configC = base64Captcha.ConfigCharacter{
		Height: 60,
		Width:  240,
		//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,CaptchaModeNumberAlphabet:数字字母混合.
		Mode:               base64Captcha.CaptchaModeNumber,
		ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
		ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
		IsShowHollowLine:   false,
		IsShowNoiseDot:     false,
		IsShowNoiseText:    false,
		IsShowSlimeLine:    false,
		IsShowSineLine:     false,
		CaptchaLen:         3,
	}
	//创建字符公式验证码.
	//GenerateCaptcha 第一个参数为空字符串,包会自动在服务器一个随机种子给你产生随机uiid.
	_, capC := base64Captcha.GenerateCaptcha("verifyKey", configC)
	//以base64编码
	ddd := capC.BinaryEncodeing()
	c.Header("Content-type", "image/jpeg")
	c.String(http.StatusOK, string(ddd))
}

var loginFunc = func(c *gin.Context) {
	w, r := c.Writer, c.Request
	var form forms.LoginForm
	var err error
	sess,err:= Store.Get(r,"user")
	if r.Method == "POST" {
		c.ShouldBind(&form)
		if err = form.Validate(); err == nil {
			user := form.GetUser()
			sess.Values["userid"] = user.Id
			sessions.Save(r,w)
			c.Redirect(http.StatusMovedPermanently, "/")
			return
		}
	}

	c.HTML(http.StatusOK, "site/login.twig", TplContext(c,pongo2.Context{
		"form": form,
		"err":  err,
	}))
}

var registerFunc = func(c *gin.Context) {
	r := c.Request
	var form forms.RegisterForm
	var err error

	if r.Method == "POST" {
		c.ShouldBind(&form)
		if err = form.Validate(); err == nil {
			if _, err := models.GetEngine().Insert(form.GetUser()); err != nil {
				fmt.Println(err.Error())
			}
			c.Redirect(http.StatusMovedPermanently, "/login")
			return
		}
	}
	c.HTML(http.StatusOK, "site/register.twig", TplContext(c,pongo2.Context{
		"form": form,
		"err":  err,
	}))
}

var logoutFunc = func(c *gin.Context) {
	w, r := c.Writer, c.Request
	sess,_:= Store.Get(r,"user")
	Store.Delete(r,w,sess)
	c.Redirect(http.StatusMovedPermanently, "/login")
}